package com.hospital.common.handler;


import com.hospital.common.base.ThreadAttributes;
import com.hospital.common.utils.ThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 预处理拦截器
 * <br>
 * 提取请求头中的用户id和用户角色值，并保存进线程变量
 * @author yhn
 * @version 1.0
 */
public class PrepareInterceptor implements HandlerInterceptor {
    public static final String USER_ID = "userId";
    public static final String ROLE_TYPE = "roleType";
    /**
     * 将用户id和用户角色值保存进线程变量
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long userId = Long.parseLong(request.getHeader(USER_ID));
        Integer roleType = Integer.parseInt(request.getHeader(ROLE_TYPE));
        ThreadLocalUtils.set(ThreadAttributes.getInstance(userId, roleType));
        return true;
    }

    /**
     * 清空线程变量
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.clear();
    }
}
